package com.hoshiicloud.market.controller.activities;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.BeanUtils;
import com.hoshiicloud.common.utils.DigestUtils;
import com.hoshiicloud.market.entity.activities.Activities;
import com.hoshiicloud.market.feign.IdGeneratorService;
import com.hoshiicloud.market.param.activities.ActivitiesAddParam;
import com.hoshiicloud.market.param.activities.ActivitiesQueryParam;
import com.hoshiicloud.market.param.activities.ActivitiesUpdateParam;
import com.hoshiicloud.market.service.activities.ActivitiesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import javax.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author campchen
 * @date in 下午 05:07 2019/8/26
 * @packagename com.hoshiicloud.market.controller.activities
 * @description
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/activities")
@Api(value = "预售促销", tags = {"预售促销"})
public class ActivitiesController {

    private final ActivitiesService activitiesService;

    private final ObjectMapper objectMapper;

    private final IdGeneratorService idGeneratorService;


    public ActivitiesController(ActivitiesService activitiesService, ObjectMapper objectMapper,
            IdGeneratorService idGeneratorService) {
        this.activitiesService = activitiesService;
        this.objectMapper = objectMapper;
        this.idGeneratorService = idGeneratorService;
    }

    /**
     * 分页查询预售促销
     *
     * @param param param
     * @return com.hoshiicloud.common.rpc.Response
     */
    @ApiOperation(value = "分页查询预售促销")
    @PostMapping("/query/page")
    public Response page(@RequestBody @Valid ActivitiesQueryParam param) {
        try {
            QueryWrapper<Activities> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq((param.getCompanyId() != null && param.getCompanyId() != 0), Activities::getCompanyId, param.getCompanyId())
                    .eq((param.getPlatformId() != null && param.getPlatformId() != 0), Activities::getPlatformId, param.getPlatformId())
                    .eq((param.getStoreId() != null && param.getStoreId() != 0), Activities::getStoreId, param.getStoreId())
                    .eq(StringUtils.isNotBlank(param.getName()), Activities::getName, param.getName())
                    .eq((param.getActivitiesStatus() != null), Activities::getActivitiesStatus, param.getActivitiesStatus())
                    .eq((param.getStatus() != null), Activities::getStatus, param.getStatus());
            IPage<Activities> page = new Page<>(Long.parseLong(param.getPageNumber()), Long.parseLong(param.getPageSize()));
            String key = param.toString() + ",Page{pageNumber=" + param.getPageNumber() + ",pageSize=" + param.getPageSize() + "}";
            String md5Key = "ActivitiesQueryParam" + DigestUtils.md5(key);
            return Response.data(activitiesService.getPage(page, queryWrapper, md5Key));
        } catch (Exception e) {
            log.error("分页查询预售促销异常 {0}", e);
            return Response.failed(e.getMessage());
        }

    }

    /**
     * 根据id查询预售促销
     *
     * @param id id
     * @return com.hoshiicloud.common.rpc.Response
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询预售促销")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response queryById(@PathVariable("id") Long id) {
        return Response.data(activitiesService.getById(id));
    }


    /**
     * 新增
     *
     * @param param param
     * @return com.hoshiicloud.common.rpc.Response
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增预售促销")
    public Response save(@RequestBody @Valid ActivitiesAddParam param) {
        Activities data = new Activities();
        try {
            BeanUtil.copyProperties(param, data, false);
            String contextJsonStr = objectMapper.writeValueAsString(param.getContext());
            log.error("Context {}", contextJsonStr);
            data.setContext(contextJsonStr)
                    .setActivitiesStatus(0);
        } catch (Exception e) {
            log.error("新增预售促销Bean转换异常 {0}", e);
            return Response.failed("新增预售促销Bean转换异常");
        }
        return Response.data(activitiesService.save(data));
    }

    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 修改预售促销
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改预售促销")
    public Response update(@RequestBody @Valid ActivitiesUpdateParam param) {
        Activities data;
        try {
            data = BeanUtils.covertType(param, Activities.class);
            // 使内部数据展示清晰
            data.setContext(param.getContext().toString());
        } catch (Exception e) {
            log.error("修改预售促销Bean转换异常 {0}", e);
            return Response.failed("新增预售促销Bean转换异常");
        }
        return Response.data(activitiesService.updateById(data));
    }
}
